package com.admin.action;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.admin.bean.ProductBean;
import com.admin.service.ProductService;
import com.admin.util.BaseUtil;
import com.admin.util.PageBean;

@Controller
@RequestMapping("/product")
public class ProductAction {

	@Autowired private ProductService productService;
	
	@RequestMapping()
	public String list(HttpServletRequest request){
		int totalCount = productService.findCount();
		int currentPage = BaseUtil.stringToInt(request.getParameter("currentPage"),1);
		PageBean<ProductBean> pageBean = new PageBean<ProductBean>(totalCount,currentPage);
		List<ProductBean> productList = productService.findProduct(pageBean.getStart(), pageBean.getPageSize());
		pageBean.setResult(productList);
		pageBean.setUrl("?1=1");
		request.setAttribute("pageBean", pageBean);
		return "productList";
	}
	
	@RequestMapping("/add")
	public ModelAndView add(HttpServletRequest request,HttpServletResponse response) throws IOException{
		String productName = request.getParameter("productName");
		int result = productService.insertProduct(productName);
		response.setContentType("text/html");
		response.getWriter().print(result);
		return null;
	}
	
	@RequestMapping("/update")
	public ModelAndView update(HttpServletRequest request,HttpServletResponse response) throws IOException{
		int productId = BaseUtil.stringToInt(request.getParameter("productId"));
		String productName = request.getParameter("productName");
		ProductBean product = new ProductBean();
		product.setProductId(productId);
		product.setProductName(productName);
		int result = productService.updateProduct(product);
		response.setContentType("text/html");
		response.getWriter().print(result);
		return null;
	}
	
	@RequestMapping("/del/{productId}")
	public ModelAndView del(@PathVariable int productId,HttpServletResponse response) throws IOException{
		int result = productService.delProduct(productId);
		response.setContentType("text/html");
		response.getWriter().print(result);
		return null;
	}
}
